/*
https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/solution/tian-chong-mei-ge-jie-dian-de-xia-yi-ge-you-ce-15/
 */
public class Solution117 {

    static class Node {
        public int val;
        public Node left;
        public Node right;
        public Node next;

        public Node() {}

        public Node(int _val) {
            val = _val;
        }

        public Node(int _val, Node _left, Node _right, Node _next) {
            val = _val;
            left = _left;
            right = _right;
            next = _next;
        }
    }

    public Node connect(Node root) {
        if (root==null){
            return null;
        }
        Node start=root;
        while (start!=null){
            Node last=null,nextStart=null;
            for (;start!=null;start=start.next){
                if (start.left!=null){
                    if (last!=null){
                        last.next=start.left;
                    }
                    last=start.left;
                    if (nextStart==null){
                        nextStart=start.left;
                    }
                }
                if (start.right!=null){
                    if (last!=null){
                        last.next=start.right;
                    }
                    last=start.right;
                    if (nextStart==null){
                        nextStart=start.right;
                    }
                }
            }
            start=nextStart;
        }
        return root;
    }

    public static void main(String[] args) {
        System.out.println(new Solution117().connect(new Node(1,new Node(2,new Node(4),new Node(5),null),new Node(3,null,new Node(7),null),null)).left.right.next.val);
    }
}
